# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def rightSideView(self, root):
        res=[]
        if root==None:
            return res
        stack=[(root,0)]
        while stack:
            tmp=stack.pop()
            if tmp[0].right:
                stack.append((tmp[0].right,tmp[1]+1))
            if tmp[0].left:
                stack.append((tmp[0].left,tmp[1]+1))
            if len(res)==tmp[1]:
                res.append(tmp[0].val)
            else:
                res[tmp[1]]=tmp[0].val
        return res

def main():
    root=TreeNode(1)
    root.left=TreeNode(2)
    root.right=TreeNode(3)
    root.left.right=TreeNode(5)
    root.right.right=TreeNode(4)
    sol=Solution()
    res=sol.rightSideView(root)
    print(res)

main()